var $=function(e){return document.getElementById(e)};
var Cactus=(function(){
	var ad_engine = "/android/ad_engine.do";
	var motion = "/common/motion.do";
	var detail = "/android/ad_detail.do";
	var downing=[];
	var current="";
	var adData=null;
	var adList={};
	var width=480;
	return {
	   	get_list:function(){
		  function cb(data){
			  adData=data;
			  Cactus.darwLi();
			}
           var param = {pageType:"j"};
		   new Cactus.execute(ad_engine,cb,param);
	   	},
	   	get_insert:function(){
	   	  function callback(data){
	   		    if(data&&data.code=='200'){
	   		        var target = $('container');
	   		        var ad = data.adInfos.length>0?data.adInfos[0]:null;
	   		        ad&&ad.ct=='d'&&(Cactus.setAppInfo(ad.adId,ad.textTitle,ad.imgPath,ad.textContent,ad.adUrl,ad.packName));
	   		        target&&ad&&(target.innerHTML='<a href="javascript:void(0);" onclick="Cactus.openUrl(\''+ad.adUrl+'\',\''+ad.ct+'\',\''+ad.packName+'\',\''+ad.adId+'\');" target="_blank">  <img src="'+ad.imgPath+'"/></a>');
	   		        ad&&Cactus.motion({type:"show",ids:ad.adId});
	   		    }   
	   	  }
	   	  var param = {pageType:"c"};
	   	  new Cactus.execute(ad_engine,callback,param);
	   	},
	   	get_banner:function(w){
	   	  w&&w<=480&&(width=w);
	   	  function callback(data){
	   		    if(data&&data.code=='200'){
	   		        Cactus.darwBanner(data.adInfos);
	   		    	//var target = $('container');
	   		        //var ad = data.adInfos.length>0?data.adInfos[0]:null;
	   		        //target&&ad&&(target.innerHTML='<a href="javascript:void(0);" onclick="Cactus.openUrl(\''+ad.adUrl+'\',\''+ad.ct+'\',\''+ad.packName+'\',\''+ad.adId+'\');" target="_blank"> <img src="'+ad.imgPath+'"/></a>');
	   		        //ad&&ad.ct=='d'&&(Cactus.setAppInfo(ad.adId,ad.textTitle,ad.imgPath,ad.textContent,ad.adUrl,ad.packName));
	   		        //ad&&Cactus.motion({type:"show",ids:ad.adId});
	   		    }   
	   	  }
	   	  var param = {pageType:"b"};
	   	  new Cactus.execute(ad_engine,callback,param);
	   	},
	   	get_detail:function(id){
	   		function cb(data){
	   			if(data&&data.code=='200'&&data.adInfos.length!=0){
	   				var ad = data.adInfos[0];
	   				$('textTitle').innerHTML=ad.textTitle;
	   				$('ad_li').innerHTML='<span><img src="'+ad.imgPath+'" width="48" height="48" border="0" alt=""></span><dl class="dl_01"><dt>'+ad.textTitle+' ('+ad.packSize+')</dt><dd>'+ad.textContent+'</dd></dl>';
	   			    $('ad_desc').innerHTML='<p>'+ad.activateDesc+'</p>';
	   			    $('img-show').innerHTML= '<img src="'+ad.imgOne+'"/><img src="'+ad.imgTwo+'"/>';
	   			    //$('down-a').innerHTML='<div id="process_'+ad.adId+'">'+Cactus.checkApp(ad.packName,ad.adId,ad.isSign)+'</div>';
	   			    $('down-a').innerHTML='<div id="process_'+ad.adId+'" class="download">'+Cactus.checkApp(ad.packName,ad.adId,0)+'</div>';
	   			}
                Cactus.downprocess();

	   		}
	   		var param = {adId:id};
	   		Cactus.execute(detail,cb,param);
	   	},
	   	motion:function(o){
	   		function cb(data){
	   		}
	   		new Cactus.execute(motion,cb,o);
	   	},
	   	execute:function(url,fn,param){
	   		var p = Cactus.paramJson(param);
	   		var desStr = Cactus.des3(p);	   		
	   		var url = url+"?p="+desStr;
			    var xhr = createxhr();
			    xhr.onreadystatechange=function(){
			       if(xhr.readyState == 4) {          
			           var data = eval("(" + xhr.responseText.replace(/\\"/g,"'")+")");
			           fn(data);
			       }
			     };
			    xhr.open('POST', url,true);
			    xhr.send(null);
	   	},
	   	onscroll:function(){
	   		//var o = $('scorll');
	   		//o&&(o.innerHTML= document.body.scrollTop||document.documentElement.scrollTop);
	   	},
	   	getMobileInfo:function(){
	   		if(typeof Weidu!='undefined'){
	   		   return Weidu.getDeviceInfo();	
	   		}
	   		return "{}";
	   	},
	   	des3:function(str){
	   		if(typeof Weidu!='undefined'){
	   		   return Weidu.encode(str);	
	   		}
	   		return str;
	   	},
	   	setAppInfo:function(id,name,icon,info,url,packname){
	   		if(typeof Weidu!='undefined'){
	   		   return Weidu.setApp(id,name,icon,info,url,packname);	
	   		}
	   	},
	   	download:function(packname,id){
	   		if(typeof Weidu!='undefined'){
	   		   Weidu.downloadApp(packname);
	   		   new process(packname,id).run();
	   		}
	   	},
	   	checkApp:function(packname,id,isSign){
   			if(typeof Weidu!='undefined'){
	   		  var i = Weidu.checkApp(packname);	   		  
	   		  if(isSign>0){
	   			   return '<a id="ahref_'+id+'" href="javascript:Cactus.sign(\''+packname+'\','+id+')">签到</a>';
	   		  }else  if(i==0){
	   			  return '<a id="ahref_'+id+'" href="javascript:Cactus.download(\''+packname+'\','+id+')">下载</a>';
	   		  }else if(i==1){
	   			  return '<a href="javascript:Cactus.openApp(\''+packname+'\')">打开</a>';
	   		  }else if(i==2){
	   			  downing.push({pn:packname,id:id});
	   		  } 
   		    }
   			 return '<a id="ahref_'+id+'" href="javascript:Cactus.download(\''+packname+'\','+id+')">下载</a>';
	   	},
	   	openApp:function(packname){
	   		if(typeof Weidu!='undefined'){
	   		   Weidu.openApp(packname);	
	   		}
	   	},
	   	downprocess:function(){
	   		while(downing.length>0){
	   			var o = downing.pop();
	   			 new process(o.pn,o.id).run();
	   		}
	   	},
	   	paramJson:function(param){
	   		
	   		var str ='{os:"android",appId:"35463",imei:"355921040541946",mac:"b4:07:f9:d5:9d:9c",ispad:"0",sh:"800",operator:"china-unicom",version:"1",usersid:"",telnum:"",brand:"samsung",imsi:"460013140607927",uuid:"4ba36d23a78c7393b4900ef38019d8ff",channel:"1",netenv:"gprs",sw:"480",appKey:"da8027255ad8456eadb4ced202d40146",telmodel:"Nexus S"}';
	   		if(typeof Weidu!='undefined'){
	   		   str=Weidu.getDeviceInfo();
	   		}
	   		var o = eval("("+str+")");
	   		o = util.ext(o,param);
	   		return util.objectToJson(o);
	   	},
	   	setTab:function(tab){
	   		if(current!=tab){
	   		   util.each(['hot','sign'],function(e){
	   			   var t = $(e);
	   			   t&&t.setAttribute("class",e==tab?"picker":"");
	   		   });
	   		   current=tab;
	   		   Cactus.darwLi();
	   		}
	   	},
	   	darwBanner:function(list){
		   	   var target = $("slides");
	   		   var _html="";
	   		   
			   util.each(list,function(ad,i){
			      _html+='<li style="width:'+width+'px"><a href="javascript:void(0);" onclick="Cactus.openUrl(\''+ad.adUrl+'\',\''+ad.ct+'\',\''+ad.packName+'\',\''+ad.adId+'\');" target="_blank"><img src="'+ad.imgPath+'" /></a></li>';
			      ad&&ad.ct=='d'&&(Cactus.setAppInfo(ad.adId,ad.textTitle,ad.imgPath,ad.textContent,ad.adUrl,ad.packName));
			   });
			   target.innerHTML=_html;
			   var showAd=list.length>0?list[0]:null;
			   showAd&&Cactus.motion({type:"show",ids:showAd.adId});
			   SLIDE.setData(list,width);
			   (list.length>1)&&(rollid=setTimeout(SLIDE.move, 20000));
	   	},
	   	darwLi:function(){
	   		 var o = $('target_ul');
	   		 var _html="";
	   		 if(adData&&adData.code=='200'){
					var o = $('target_ul');
					var adIds = "";
					
					var list =[];
					util.each(adData.adInfos,function(e){
						if(current=='sign' && e.isSign>0){
							list.push(e);
						}else if(current!='sign' && e.isSign<=0){
						    list.push(e);
						}
					});
					util.each(list,function(ad,i){
						Cactus.setAppInfo(ad.adId,ad.textTitle,ad.imgPath,ad.textContent,ad.adUrl,ad.packName);
						_html+='<li>';
						_html+='<span><img src="'+(ad.imgPath||'')+'" width="48" height="48" border="0" alt=""></span>';
						_html+='<dl class="dl_02" ><dt>'+ad.integral+(adData.unit||'')+'</dt><dd id="process_'+ad.adId+'">'+Cactus.checkApp(ad.packName,ad.adId,ad.isSign)+'</dd></dl>';
						_html+='<dl class="dl_01" onclick="javascript:Cactus.detail('+ad.adId+');"><dt>'+(ad.textTitle||"")+' <span style="color:#666">'+ad.packSize+'</span><span style="">('+(ad.activate||"")+')</span></dt>	<dd>'+(ad.textContent||'')+'</dd></dl>';
						_html+='</li>';
						adIds+=(i==0)?ad.adId:(","+ad.adId);
					});
					if(list.length==0){
					   _html+='<li style="text-align: center;">暂无数据.</li>';	
					}
					o&&(o.innerHTML=_html);
					if(adIds!=""){
					  Cactus.motion({type:"show",ids:adIds});	
					}
					Cactus.downprocess();
				}
	   	},
	   	detail:function(id){
	   		id&&Cactus.motion({type:"click",ids:id});
	   		window.location="/cactus/detail.html?id="+id
	   	},
	   	close:function(){
	   		if(typeof Weidu!='undefined'){
	   		   Weidu.close();
	   		}
	   	},
	   	sign:function(packname,id){
	   		Weidu.checkIn(packname,id);
	   		location.reload() 
	   		//window.location.reload();
	   	},
	   	openUrl:function(url,ct,pn,adId){
	   		if(typeof Weidu!='undefined'){
	   		   ct=='d'?Weidu.downloadApp(pn):Weidu.openWeb(url);
	   		   Cactus.motion({type:"click",ids:adId});
	   		}
	   	}
	}
})();

var util = {
	each:function(r,fn,bn,en){
      var  b=bn||0,e=en||r.length;
      for(var i=b;i<e;i++){
         var result = fn(r[i],i);
         if(result!=undefined) return result;
      }
   },
   objectToJson:function(o){
	   var json="{";
	   var b =true;
	   for(var p in o){
		   json+= b?( p+":\""+o[p]+"\""):( ","+p+":\""+o[p]+"\"");
		   if(b){b=false}
	   }
	   json+="}";
	   return json;
   },
   ext:function(o,e){
	   if(!e) return o;
	   for(var p in e){
		   o[""+p+""]=e[p];
	   }
	   return o;
   }
};
function process(packname,id){
  var T = this;
  T.id = id;
  T.packname = packname;
  T.target = $('process_'+id);
  T.lineid = null;
  T.run = function(){
	  function _run(){
		  if(typeof Weidu!='undefined'){
			    if(T.target){
			    	var rate=Weidu.getProgress(packname);
		   		    //T.target.innerHTML= rate>=100?('<a href="javascript:Cactus.openApp(\''+packname+'\')">安装</a>'):('<progress max="100" value="'+rate+'"><ie style="width:'+rate+'%;"></ie></progress>');
		   		    T.target.innerHTML= rate>=100?('<a href="javascript:Cactus.openApp(\''+packname+'\')">安装</a>'):('<div class="progress"><div class="ie" style="width:'+rate+'%"></div><div class="point"> '+rate+'%</div> </div>');
		   		    //<progress max="100" value="20"><ie style="width:20%;"></ie></progress>
		   		    if(rate>=100){
		   		       clearTimeout(T.lineid)	
		   		    }else{
		   		      T.lineid=setTimeout(_run,1000);
		   		    }
			    }else{
			    	alert(" no no no");
			    }
   		  }
	  };
	  _run();
  }
};
			           
//xhr obj
function createxhr(){
  if(typeof XMLHttpRequest!='undefined'){
      return new XMLHttpRequest();
  }else{
        var arrSignatures = [ 'Microsoft.XMLHTTP', 'MSXML.XMLHTTP','Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0','Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0','Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP' ];
        for (var i=0; i < arrSignatures.length; i++) {
            try {return new ActiveXObject(arrSignatures[i]);} catch (oError) { }
        }          
        throw new Error("MSXML is not installed on your system.");         
  }
  throw new Error("MSXML is not installed on your system.");           
};


var SLIDE=(function(){
	var lineid,rollid;
    var current=0;
    var data;
    var length=0;
    var slides = $("slides");
    var slide_width=480;
	return {
		setData:function(list,width){
		   data=list;
		   length=list.length;
		   slide_width=width;
		},
		move:function(){
			//t：current time（当前时间）; bi：beginning value（初始值）; c： change in value（变化量);d：duration（持续时间）。
			 var t=0;
		     var b=parseInt(slides.style.left||0);
		     var c=(current==(length-1))?(current)*slide_width:-slide_width;
		     var d=40;
		     (current==(length))&&(current=0);
		     function _run(){
				if(t<d){
					t++;
					var w = fix((t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b,1);
					slides.style.left=(w+"px");
					lineid = setTimeout(_run, 30);
				}else{
				  rollid=setTimeout(SLIDE.move, 20000);
				}
		     };
		     _run();
		     current++;
		     
		     var ad;
            (current<data.length)?(ad=data[current]):ad=data[0];
		     ad&&Cactus.motion({type:"show",ids:ad.adId});
		     
		}
	}
})();

    function fix(x, n) {
		with(Math){
			var N = Math.pow(10,n);
			return Math.round(x * N) / N;
		}
	}
    function getParameter(p){
	  var parseStr =  window.location.search.slice(1);
	  var paraList = parseStr.split(/\&/g);
	  for(var i=0;i<paraList.length;i++){
	     var pattern = new RegExp("^"+p+"[?=\\=]","g");
	     if(pattern.test(paraList[i])){
	        return decodeURIComponent(paraList[i].split(/\=/g)[1]);
	     }
	  }
	  return null;
	}
  